package org.janon.httpproxy.client;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class IgnoreSite
{
	private static IgnoreSite instance = null;
	private java.util.List<IgnoreSiteData> ignoreSites;
	private boolean isIgnore = true;
	private IgnoreSite(){
		ignoreSites = new java.util.ArrayList<IgnoreSiteData>();
		init();
	}
	
	private void init(){
		try
		{
			BufferedReader br = new BufferedReader(new FileReader(new File("site.ini")));
			String str = br.readLine();
			if("[use]".equalsIgnoreCase(str))
			{
				isIgnore = false;
			}
			while(true)
			{
				str = br.readLine();
				if(str==null)
					break;
				str = str.trim();
				if(str.length()!=0)
				{
					add(str);
				}
			}
		}
		catch(Exception ex)
		{
		}
	}
	
	public static IgnoreSite getInstance(){
		if(instance == null){
			instance = new IgnoreSite();
		}
		return instance;
	}
	
	public void add(String site){
		boolean f = !isIgnore(site);
		if(isIgnore?f:!f)
			ignoreSites.add(new IgnoreSiteData(site.toUpperCase()));
	}
	
	public void remove(String site){
		ignoreSites.remove(new IgnoreSiteData(site.toUpperCase()));
	}
	
	public boolean isIgnore(String site){
		boolean rtn = false;
		site = site.trim().toUpperCase();
		if(site.indexOf(":")!=-1){
			String[] s = site.split(":");
			if(!s[1].equals("-1")){
				rtn = ignoreSites.contains(new IgnoreSiteData(s[0]+":-1"));
			}
		} else {
			rtn = ignoreSites.contains(new IgnoreSiteData(site+":-1"));
		}
		if(!rtn)
			rtn = ignoreSites.contains(new IgnoreSiteData(site));
		return isIgnore?rtn:!rtn;
	}
	
	private class IgnoreSiteData
	{
		String site = "";
		public IgnoreSiteData(String site)
		{
			this.site = site;
		}
		
		public void set(String site)
		{
			this.site = site;
		}
		
		public String get()
		{
			return site;
		}

		public boolean equals(Object obj)
		{
			if(obj instanceof IgnoreSiteData)
			{
				IgnoreSiteData d = (IgnoreSiteData)obj;
				if(get()==null&&d.get()==null)
				{
					return true;
				}
				else if(get()==null||d.get()==null)
				{
					return false;
				}
				return get().indexOf(d.get())!=-1;
			}
			return false;
		}
	}
}
